package com.itheima.crm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itheima.crm.pojo.BaseDict;
import com.itheima.crm.pojo.Customer;
import com.itheima.crm.pojo.QueryVo;
import com.itheima.crm.service.BaseDictService;
import com.itheima.crm.service.CustomerService;
import com.itheima.crm.utils.Page;

/**
 * 客户管理Controller
 * <p>Title: CustomerController</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
	
	@Autowired
	private BaseDictService baseDictService;
	@Autowired
	private CustomerService customerService;
	
	@Value("${customer.source.code}")
	private String CustomerSourceCode;
	@Value("${customer.industry.code}")
	private String CustomerIndustryCode;
	@Value("${customer.level.code}")
	private String CustomerLevelCode;

	@RequestMapping("/list")
	public String showCustomerList(Model model, QueryVo queryVo) throws Exception {
		
		String custName = queryVo.getCustName();
		if (custName != null && !"".equals(custName)) {
			custName = new String(custName.getBytes("iso8859-1"), "utf-8");
			queryVo.setCustName(custName);
		}
		//查询字典表初始化下拉列表
		List<BaseDict> custSourceList = baseDictService.getBaseDictList(CustomerSourceCode);
		List<BaseDict> custIndustryList = baseDictService.getBaseDictList(CustomerIndustryCode);
		List<BaseDict> custLevelList = baseDictService.getBaseDictList(CustomerLevelCode);
		//查询客户列表
		Page<Customer> page = customerService.getCustList(queryVo);
		//把page放到request中
		model.addAttribute("page", page);
		
		//把列表传递给jsp页面
		model.addAttribute("fromType", custSourceList);
		model.addAttribute("industryType", custIndustryList);
		model.addAttribute("levelType", custLevelList);
		
		//页面回显
		model.addAttribute("custName", queryVo.getCustName());
		model.addAttribute("custSource", queryVo.getCustSource());
		model.addAttribute("custIndustry", queryVo.getCustIndustry());
		model.addAttribute("custLevel", queryVo.getCustLevel());
		
		
		return "customer";
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public Customer getCustomerById(Long id) {
		Customer customer = customerService.getCustomerById(id);
		return customer;
	}
	
	@RequestMapping(value="/update", method=RequestMethod.POST)
	@ResponseBody
	public String updateCustomer(Customer customer) {
		customerService.updateCustomerById(customer);
		//直接向浏览器响应字符串需要使用@ResponseBody
		return "OK";
		
	}
}
